import cv2
import base64
import requests
from datetime import datetime, timedelta
import paramiko
import time
import sys

class RUNSSH2:
    def __init__(self, ip='raspberrypi.local', port=22, username='pi', password='raspberry', filedir='/home/pi/Desktop/', api_key="EO8531qaS2w7p1WQOTnlslYZ", secret_key="PwiyJITOASccm1Ph6LUWvtlzEOWkeqDp"):
        self.IP = ip
        self.PORT = port
        self.USERNAME = username
        self.PASSWORD = password
        self.FILEDIR = filedir
        self.API_KEY = api_key
        self.SECRET_KEY = secret_key
        self.ACCESS_TOKEN = None
        self.ACCESS_TOKEN_EXPIRES = None

    def capture_and_ocr(self):
        with cv2.VideoCapture(0) as cap:
            while True:
                ret, frame = cap.read()
                if not ret:
                    print("Could not read from camera")
                    break
                
                cv2.imshow('Camera Preview', frame)
                
                if cv2.waitKey(1) & 0xFF == ord('c'):
                    break

        _, buffer = cv2.imencode('.jpg', frame)
        image_base64 = base64.b64encode(buffer).decode('utf-8')
        access_token = self.get_access_token()
        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token={access_token}"
        payload = {'image': image_base64}
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        try:
            response = requests.post(url, headers=headers, data=payload)
            print(response.text)
        except requests.RequestException as e:
            print(f"Error occurred during API request: {e}")

    def get_access_token(self):
        if self.ACCESS_TOKEN is None or datetime.now() > self.ACCESS_TOKEN_EXPIRES:
            url = "https://aip.baidubce.com/oauth/2.0/token"
            params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
            response = requests.post(url, params=params)
            self.ACCESS_TOKEN = response.json().get("access_token")
            self.ACCESS_TOKEN_EXPIRES = datetime.now() + timedelta(seconds=response.json().get("expires_in"))
        return self.ACCESS_TOKEN

    def debugprint(self,varl):
        print(varl)

    def filecopy(self):
        
        self.debugprint("ssh:"+self.IP+":"+str(self.PORT))
        
        transport = paramiko.Transport(self.IP, self.PORT)
        transport.connect(username=self.USERNAME, password=self.PASSWORD)
        
        sftp = paramiko.SFTPClient.from_transport(transport)#如果连接需要密钥，则要加上一个参数，hostkey="密钥"
        self.debugprint("copy file...")
        sftp.put('code.py', self.FILEDIR+'mindpluscode.py')#将本地的Windows.txt文件上传至服务器
        transport.close()#关闭连接
        self.debugprint("copy done")

    def filerun(self):
        self.debugprint("ssh:"+self.IP)
        # 实例化一个ssh客户端对象
        ssh = paramiko.SSHClient()
        # 自动在know_host中添加自己要连的机器，忽略这个验证，注意传入的参数paramiko.AutoAddPolicy()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接信息
        ssh.connect(hostname=self.IP, port=self.PORT, username=self.USERNAME, password=self.PASSWORD)
        self.debugprint("kill python")
        # 传输命令，这里有三个返回值，按顺序第一个是标准输入，即你输入的命令，第二个标准输出，即命令返回值
        # 第三个标准错误，报错的时候会返回给这个值，同时返回值不是固定而是变化的时候也会返回给这个值一个错误
        #stdin, stdout, stderr = ssh.exec_command('ps -ef |grep python3|cut -c 9-15|xargs kill -9') #停止正在运行的python程序
        #stdin, stdout, stderr = ssh.exec_command('pkill -9 python3') #停止正在运行的python程序
        stdin, stdout, stderr = ssh.exec_command("ps -ef | grep mindpluscode.py | awk '{print $2}' | xargs kill -9") #停止正在运行的mindpluscode程序
        time.sleep(2)
        self.debugprint("run python")
        stdin, stdout, stderr = ssh.exec_command('cd '+self.FILEDIR+'; python3 mindpluscode.py > ~/Desktop/log.txt') 
        
        #stdin, stdout, stderr = ssh.exec_command('cd '+self.FILEDIR+'; python3 mindpluscode.py &') 
        '''
        self.debugprint("#root@RVBoards received: ")
        ##返回信息
        out,err = stdout.read().decode('utf-8'),stderr.read().decode('utf-8')
        if err:
            print(err)
        else:
            print(out)
        
        self.debugprint("----------")
        '''
        # 关闭客户端
        ssh.close()
        self.debugprint("run done")

    def run(self):
        self.capture_and_ocr()  # 捕获图像并进行OCR识别
        self.filecopy()         # 拷贝文件到远程主机
        self.filerun()          # 运行程序
        sys.exit(0)             # 退出程序
        